import React, { useState, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, message, Modal, Alert, Tabs } from 'antd';
import { connect, FormattedMessage, useIntl } from 'umi';
import MyDataTable from '@/components/MyDataTable';
import request from '@/utils/request';
import DemandEntry from './demandEntry';
import QuickMenu from '@/components/QuickMenu';

const { TabPane } = Tabs;
const apiURL = '/api/services/app/Demands/';

const ViewPage: React.FC<any> = (props) => {
  const [params, setParams] = useState({});
  const [freshNum, setFreshNum] = useState(0);
  const [record, setRecord] = useState([]);
  const [data, setData] = useState<any>({});
  const [visible, setVisible] = useState(false);
  const intl = useIntl();

  let demandEntry: any = DemandEntry;
  const formRef = (ref: any) => {
    demandEntry = ref;
  };

  const doubleClick = (data: any) => {
    setData(data);
    setVisible(true);
  };

  const apprvPO = () => {
    if (!record || record.length <= 0) {
      message.warning(intl.formatMessage({id:'pages.selectAtLeastOneRecord'}));
      return;
    }
    const data: any = [];
    record.forEach((element: any) => {
      data.push(element.id);
    });
    request(apiURL + 'DoApprv', {
      method: 'POST',
      data,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({id:'pages.approve.success'}));
        }
        setFreshNum(freshNum + 1);
      }
    });
  };

  const callback = () => {
    setFreshNum(freshNum + 1);
  };

  const tabChange = (key: any) => {
    if (key === 'APPRV') {
      setParams({ apprv: 1, open: -1 });
    } else if (key === 'NOAPPRV') {
      setParams({ apprv: 0, open: -1 });
    } else if (key === 'CLOSE') {
      setParams({ apprv: -1, open: 0 });
    } else if (key === 'OPEN') {
      setParams({ apprv: -1, open: 1 });
    } else {
      setParams({ apprv: -1, open: -1 });
    }
    setFreshNum(freshNum + 1);
  };

  const openWin = () => {
    setData({ id: 0 });
    setVisible(true);
  };

  const rowSelection = {
    onChange: (_selectedKeys: any, selectedRows: any) => {
      setRecord(selectedRows);
    },
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.reqNum" />,
      dataIndex: 'id',
      width: 80,
      valueType: 'text',
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      width: 120,
      valueType: 'text',
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      valueType: 'text',
    },
    {
      title: <FormattedMessage id="pages.quantity" />,
      dataIndex: 'reqQty',
      width: 60,
      valueType: 'digit',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.reqDate" />,
      dataIndex: 'reqDate',
      width: 120,
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.approve" />,
      dataIndex: 'approve',
      width: 60,
      valueType: 'select',
      valueEnum: {
        false: { text: intl.formatMessage({ id: 'pages.unAprvd' }), status: 'Error' },
        true: { text: intl.formatMessage({ id: 'pages.aprvd' }), status: 'Success' },
      },
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.openline" />,
      dataIndex: 'openLine',
      width: 60,
      valueType: 'select',
      valueEnum: {
        true: { text: intl.formatMessage({ id: 'pages.openline' }), status: 'Error' },
        false: { text: intl.formatMessage({ id: 'pages.complete' }), status: 'Success' },
      },
      hideInSearch: true,
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Tabs defaultActiveKey="ALL" onChange={tabChange} type="card">
        <TabPane tab={<FormattedMessage id="pages.all" />} key="ALL" />
        <TabPane tab={<FormattedMessage id="pages.approved" />} key="APPRV" />
        <TabPane tab={<FormattedMessage id="pages.unApprove" />} key="NOAPPRV" />
        <TabPane tab={<FormattedMessage id="pages.closed" />} key="CLOSE" />
        <TabPane tab={<FormattedMessage id="pages.openline" />} key="OPEN" />
      </Tabs>
      <MyDataTable
        title={<FormattedMessage id="menu.purchase.poDemand" />}
        act="GetList"
        columns={columns}
        freshNum={freshNum}
        pageSize={10}
        control="Demands"
        doubleClick={doubleClick}
        rowSelection={rowSelection}
        params={params}
        pagination={true}
        toolBarRender={() => [
          <Alert
            message={<FormattedMessage id="pages.tips.dbclick.edit" />}
            type="warning"
            showIcon
            closable
          />,
          <Button type="primary" onClick={openWin}>
            <FormattedMessage id="pages.new" />
          </Button>,
          <Button danger onClick={apprvPO}>
            <FormattedMessage id="pages.approve" />
          </Button>,
          <QuickMenu path="/purchase/poDemand" icon="icon-document" title="pages.PODemand" />,
        ]}
        search={{
          filterType: 'nomal',
        }}
      />
      <Modal
        title={<FormattedMessage id="pages.edit" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => setVisible(false)}
        footer={false}
        width={800}
      >
        <DemandEntry onRef={formRef} fetchData={callback} id={data.id} />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(ViewPage);
